package com.sddnytsh.body_buildingsystem

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.sddnytsh.body_buildingsystem.screens.AboutScreen
import com.sddnytsh.body_buildingsystem.screens.ChatScreen
import com.sddnytsh.body_buildingsystem.screens.CommentDetailScreen
import com.sddnytsh.body_buildingsystem.screens.CreatePostScreen
import com.sddnytsh.body_buildingsystem.screens.DietScreen
import com.sddnytsh.body_buildingsystem.screens.FollowingScreen
import com.sddnytsh.body_buildingsystem.screens.HelpAndFeedbackScreen
import com.sddnytsh.body_buildingsystem.screens.LoginScreen
import com.sddnytsh.body_buildingsystem.screens.MainScreen
import com.sddnytsh.body_buildingsystem.screens.MyCommentsScreen
import com.sddnytsh.body_buildingsystem.screens.MyFavoritesScreen
import com.sddnytsh.body_buildingsystem.screens.MyPostsScreen
import com.sddnytsh.body_buildingsystem.screens.PostDetailScreen
import com.sddnytsh.body_buildingsystem.screens.ProfileScreen
import com.sddnytsh.body_buildingsystem.screens.RegisterScreen
import com.sddnytsh.body_buildingsystem.screens.SettingsScreen
import com.sddnytsh.body_buildingsystem.topic.Comment
import com.sddnytsh.body_buildingsystem.ui.theme.BodybuildingSystemTheme
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.topic.Profile
import com.sddnytsh.body_buildingsystem.config.NetworkConfig
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import com.google.gson.Gson
import com.google.gson.JsonObject

class MainActivity : ComponentActivity() {

    /**
     * 初始化用户头像 - 在用户登录后获取当前用户的头像
     */
    private fun initializeUserAvatar() {
        val currentUser = UserState.currentUser
        if (currentUser != null) {
            Log.d("MainActivity", "🔥 初始化用户头像，用户ID: ${currentUser.id}")
            CoroutineScope(Dispatchers.IO).launch {
                try {
                    // 获取用户资料信息
                    val profile = fetchUserProfile(currentUser.id)
                    profile?.let {
                        Log.d("MainActivity", "🔥 获取到用户头像: ${it.avatar}")
                        // 更新全局头像状态
                        UserState.updateUserAvatar(it.avatar)
                    }
                } catch (e: Exception) {
                    Log.e("MainActivity", "🔥 获取用户头像失败: ${e.message}")
                }
            }
        } else {
            Log.d("MainActivity", "🔥 用户未登录，跳过头像初始化")
        }
    }

    /**
     * 监听用户登录状态变化，登录后初始化头像
     */
    private fun observeUserLoginState() {
        // 这里可以添加用户登录状态的监听逻辑
        // 当用户登录成功后，自动初始化头像
    }

    /**
     * 获取用户资料信息
     */
    private suspend fun fetchUserProfile(userId: Long): Profile? {
        return try {
            val client = OkHttpClient.Builder()
                .connectTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(8, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .connectionPool(okhttp3.ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
                .build()
            val request = Request.Builder()
                .url("${NetworkConfig.BASE_URL}/api/user-profile/$userId")
                .build()
            
            withContext(Dispatchers.IO) {
                try {
                    val response = client.newCall(request).execute()
                    val body = response.body?.string() ?: return@withContext null
                    val json = Gson().fromJson(body, JsonObject::class.java)
                    if (json.get("success")?.asBoolean == true) {
                        val data = json.getAsJsonObject("data")
                        Profile(
                            userId = data.get("userId")?.asLong ?: userId,
                            name = data.get("name")?.asString ?: "用户",
                            des = data.get("des")?.asString ?: "",
                            avatar = data.get("avatar")?.asString, // 头像URL
                            gender = data.get("gender")?.asString ?: "保密",
                            height = data.get("height")?.asDouble ?: 0.0,
                            weight = data.get("weight")?.asDouble ?: 0.0,
                            birthday = data.get("birthday")?.asString ?: "1990-01-01",
                            location = data.get("location")?.asString ?: ""
                        )
                    } else {
                        null
                    }
                } catch (e: Exception) {
                    Log.e("MainActivity", "网络请求失败: ${e.message}")
                    null
                }
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "获取用户资料失败: ${e.message}")
            null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("SimpleAvatarImage", ">>> MainActivity onCreate")
        Log.e("MainActivity", ">>> 应用启动成功！")
        android.widget.Toast.makeText(this, "应用启动成功！", android.widget.Toast.LENGTH_LONG).show()
        
        // 🔥 监听用户登录状态变化
        observeUserLoginState()
        
        enableEdgeToEdge()
        setContent {
            BodybuildingSystemTheme {
                val navController = rememberNavController()

                NavHost(navController = navController, startDestination = "login") {
                    composable("login") {
                        LoginScreen(navController = navController)
                    }
                    composable("register") {
                        RegisterScreen(navController = navController)
                    }
                    composable("main") {
                        MainScreen(navController = navController)
                    }
                    composable("profile") {
                        ProfileScreen(navController = navController)
                    }
                    composable("postDetail/{postId}") { backStackEntry ->
                        val postId =
                            backStackEntry.arguments?.getString("postId")?.toIntOrNull() ?: 0
                        PostDetailScreen(navController, postId)
                    }
                    composable("comment_detail/{commentId}") { backStackEntry ->
                        val commentId = backStackEntry.arguments?.getString("commentId")?.toLongOrNull() ?: 0L
                        CommentDetailScreen(navController, commentId)
                    }
                    composable("about") {
                        AboutScreen(navController = navController)
                    }
                    composable("help") {
                        HelpAndFeedbackScreen(navController = navController)
                    }
                    composable("settings") {
                        SettingsScreen(navController = navController)
                    }
                    composable("createPost") {
                        CreatePostScreen(navController = navController)
                    }
                    composable("diet") {
                        DietScreen(navController = navController)
                    }
                    composable("chat/{contactId}") { backStackEntry ->
                        val contactId = backStackEntry.arguments?.getString("contactId")?.toLongOrNull() ?: 0L
                        ChatScreen(navController, contactId)
                    }
                    composable("myPosts") {
                        MyPostsScreen(navController = navController)
                    }
                    composable("myComments") {
                        MyCommentsScreen(navController = navController)
                    }
                    composable("myFavorites") {
                        MyFavoritesScreen(navController = navController)
                    }
                    composable("following") {
                        FollowingScreen(navController = navController)
                    }
                }
            }
        }
    }
}
